package com.bot.rf.util;


import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.*;

import static com.bot.rf.util.MyLogger.LOGGER;

/**
 * @program: report-form-demo
 * @description: 邮件工具类
 * @author: zyy
 * @create: 2021-02-24 14:48
 **/
public class MyMail {

    /**
     * 是否开启邮件（读配置文件）
     */
    public static boolean ENABLE_EMAIL = false;

    /**
     * 发送者账号（读配置文件）
     */
    public static String EMAIL_FROM_ACCOUNT = "";

    /**
     * 发送者密码（读配置文件）
     */
    public static String EMAIL_FROM_PASSWORD = "";

    /**
     * 发送者名字（读配置文件）
     */
    public static String EMAIL_FROM_USERNAME = "";

    /**
     * 邮件服务器主机（读配置文件）
     */
    public static String EMAIL_HOST = "";

    /**
     * 邮件服务器端口（读配置文件）
     */
    public static String EMAIL_PORT = "";

    /**
     * 备用接收者账号（读配置文件）
     */
    public static String TO_ACCOUNT = "";

    /**
     * 备用接收者密码（读配置文件）
     */
    public static String TO_USERNAME = "";

    /**
     * 多个接收者账号-密码（读配置文件）
     */
    public static Map<String, String> TO_ACCOUNT_MAP = new HashMap<>();

    public static Properties props;

    public MyMail(){
        props = System.getProperties();
        //需要请求认证
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        //6分钟超时，预防网络较差时传输较慢
        props.setProperty("mail.smtp.timeout", "360000");
        //发件人的邮箱的SMTP服务器地址
        props.put("mail.smtp.host", EMAIL_HOST);
        props.put("mail.smtp.port", EMAIL_PORT);
    }

    /**
     * 发送纯文本邮件
     *
     * @param subject
     * @param content
     * @return
     */
    public boolean sendEmail(String subject, String content){
        LOGGER.info("开始发送邮件");
        Session session = Session.getInstance(props);
        // 设置为debug模式，发送时可以查看详细的log
        session.setDebug(false);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(EMAIL_FROM_ACCOUNT,EMAIL_FROM_USERNAME,"UTF-8"));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(TO_ACCOUNT, TO_USERNAME,"UTF-8"));
            String subjectEncode = MimeUtility.encodeWord(subject, "UTF-8","Q");
            message.setSubject(subjectEncode);
            message.setContent(content, "text/html;charset=utf-8");
            // 设置发送时间
            message.setSentDate(new Date());
            // 保存设置
            message.saveChanges();
        } catch (Exception e) {
            LOGGER.error("邮件发送失败！");
            LOGGER.error(e.getMessage());
            return false;
        }
        // 根据session获取邮件传输对象
        Transport transport = null;
        try{
            transport = session.getTransport();
            transport.connect(EMAIL_FROM_ACCOUNT,EMAIL_FROM_PASSWORD);
            transport.sendMessage(message,message.getAllRecipients());
            transport.close();
        }catch (Exception e){
            LOGGER.error("邮件发送失败！");
            LOGGER.error(e.getMessage());
            return false;
        }
        LOGGER.info("邮件发送成功！");
        return  true;
    }

    /**
     * 发送邮件，带附件
     * @param subject
     * @param content
     * @param fileName
     * @return
     */
    public boolean sendEmail(String subject,String content, String fileName){
        LOGGER.info("开始发送邮件，邮件主题：" + subject);
        Session session = Session.getInstance(props);
        session.setDebug(false);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(EMAIL_FROM_ACCOUNT,EMAIL_FROM_USERNAME,"UTF-8"));
            if (ENABLE_EMAIL){
                List<InternetAddress> iadList = new ArrayList<InternetAddress>();
                for (Map.Entry<String, String> entry: TO_ACCOUNT_MAP.entrySet()) {
                    iadList.add(new InternetAddress(entry.getKey(), entry.getValue(),"UTF-8"));
                }
                iadList.add(new InternetAddress(TO_ACCOUNT, TO_USERNAME,"UTF-8"));
                InternetAddress[] iadArray = new InternetAddress[iadList.size()];
                message.setRecipients(MimeMessage.RecipientType.TO,iadList.toArray(iadArray));
            }else {
                message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(TO_ACCOUNT, TO_USERNAME,"UTF-8"));
            }
            String subjectEncode = MimeUtility.encodeWord(subject, "UTF-8","Q");
            message.setSubject(subjectEncode);
            // 创建附件
            MimeBodyPart attachment = new MimeBodyPart();
            DataHandler dataHandler = new DataHandler(new FileDataSource(fileName));
            attachment.setDataHandler(dataHandler);
            attachment.setFileName(MimeUtility.encodeText(dataHandler.getName()));
            // 文本
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(content,"text/html;charset=utf-8");
            // 设置文本和附件的关系（合成一个大的混合节点）
            MimeMultipart allMultipart = new MimeMultipart();
            allMultipart.addBodyPart(attachment);
            allMultipart.addBodyPart(text);

            message.setContent(allMultipart, "text/html;charset=utf-8");
            // 设置发送时间
            message.setSentDate(new Date());
            // 保存设置
            message.saveChanges();
        }catch (Exception e){
            LOGGER.error("邮件发送失败！");
            LOGGER.error(e.getMessage());
            return  false;
        }
        // 根据session获取邮件传输对象
        Transport transport = null;
        try{
            transport = session.getTransport();
            transport.connect(EMAIL_FROM_ACCOUNT,EMAIL_FROM_PASSWORD);
            transport.sendMessage(message,message.getAllRecipients());
            transport.close();
        }catch (Exception e){
            LOGGER.error("邮件发送失败！");
            LOGGER.error(e.getMessage());
            return false;
        }
        LOGGER.info("邮件发送成功！");
        return  true;
    }
}
